﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Net.Sockets;
using System.Text;
using System.Diagnostics;

namespace Ntalk
{
    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }

        public Socket connection { get; set; }
        public bool connected { get; set; }

        private String trailingMessage = null;
        private int bufferSize = 512;

        public void CreateConnection(string serverAddress, int port)
        {
            if (connection == null)
            {
                connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            else
            {
                connection.Dispose();
                connection.Close();
                connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            var connectionOperation = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(serverAddress, port) };
            connectionOperation.Completed += OnConnectionToServerCompleted;
            connection.ConnectAsync(connectionOperation);
        }

        private void OnConnectionToServerCompleted(object sender, SocketAsyncEventArgs e)
        {
            connected = true;
            receiveMessage();
        }

        private void OnMessageReceivedFromServer(object sender, SocketAsyncEventArgs e)
        {
            if (e.BytesTransferred <= 0)
            {
                receiveMessage();
                return;
            }
            var message = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
            if (trailingMessage != null)
            {
                message = message + trailingMessage;
                trailingMessage = null;
            }
            int start = 0;
            int end = 0;
            while (start < message.Length && ((end = message.IndexOf('\n', start)) != -1))
            {
                String res = message.Substring(start, end - start);
                String[] arrayValue = res.Split(' ');
                if (arrayValue[0] == "ping")
                {
                  sendMessage("ping 60");
                }
                else if (res.IndexOf("user_cmd") == 0 && res.IndexOf("msg") != -1)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content;
                        if (currentPage is IPageReceiver)
                        {
                            ((IPageReceiver)currentPage).receiveMessage(getName(res), getMessage(res));
                        }
                    });
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content;
                        if (currentPage is IPageReceiver)
                        {
                            ((IPageReceiver)currentPage).receiveData(res);
                        }
                    });
                }
                start = end + 1;
            }
            if (start < message.Length)
                trailingMessage = message.Substring(start);
            if (connected)
                receiveMessage();
        }

        public void receiveMessage()
        {
            var responseListener = new SocketAsyncEventArgs();
            responseListener.Completed += OnMessageReceivedFromServer;
            var responseBuffer = new byte[bufferSize];
            responseListener.SetBuffer(responseBuffer, 0, bufferSize);
            try
            {
                connection.ReceiveAsync(responseListener);
            }
            catch (ObjectDisposedException e)
            { }
        }

        public void sendMessage(String packet)
        {
            var asyncEvent = new SocketAsyncEventArgs { };
            var buffer = Encoding.UTF8.GetBytes(packet + Environment.NewLine);
            asyncEvent.SetBuffer(buffer, 0, buffer.Length);
            connection.SendAsync(asyncEvent);
        }

        private string getName(String msg)
        {
            string[] blocks;
            string name;
            char []separators = {':','|'};
            blocks = msg.Split(separators);
            name = blocks[3].Split('@').First();
            return name;
        }

        private string getMessage(String msg)
        {
            string[] blocks;
            string message;
            blocks = msg.Split('|');
            message = blocks[1].Split(' ')[2];
            return message;
        }


        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            connection = null;
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion

        private void Application_Exit(object sender, EventArgs e)
        {

        }
    }
}